import { useRef, useEffect, useMemo } from "react";
import ChatMessage from "./ChatMessage";
import styles from "../../App.module.css";
import { useChat } from "../store/useChat";

const MessageList = () => {
    const conversations = useChat((state) => state.conversations);
    const currentId = useChat((state) => state.currentConversationId);
    const currentConversation = conversations.find(
        (e) => e.id === currentId,
    ) || { messages: [] };
    const messages = currentConversation.messages;
    const containerRef = useRef<HTMLDivElement>(null);

    useEffect(() => {
        if (containerRef.current) {
            containerRef.current.scrollTo({
                top: containerRef.current.scrollHeight,
                behavior: "smooth",
            });
        }
    }, [messages]);
    const messageList = useMemo(() => {
        const excludeRoleMessages = ["tool", "system"];
        return messages
            .filter((e) => !excludeRoleMessages.includes(e.role))
            .map((message, index) => (
                <ChatMessage
                    key={index}
                    content={message.content}
                    role={message.role}
                    timestamp={message.timestamp}
                />
            ));
    }, [messages]);

    return (
        <div ref={containerRef} className={styles.messageList}>
            {messageList}
        </div>
    );
};

export default MessageList;
